"use client";

import React, { useState, useEffect } from 'react';
import { Upload, message, Space, List, Button, Typography, Progress } from 'antd';
import { InboxOutlined, DownloadOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { uploadPlanAttachment, downloadPlanAttachment, getPlanAttachmentInfo, AttachmentInfo } from '@/lib/file';
import apiClient from '@/lib/interceptor';
import { useRouter, useSearchParams } from 'next/navigation';

const { Dragger } = Upload;
const { Text } = Typography;

interface AttachmentPageProps {
  onCancel?: () => void;
  planId?: string;
}

export default function Page({ onCancel, planId: propPlanId }: AttachmentPageProps = {}) {
  const router = useRouter();
  const searchParams = useSearchParams();
  // 优先使用props传入的planId，如果没有则使用URL参数
  const planId = propPlanId || searchParams.get('planId');

  const [attachment, setAttachment] = useState<AttachmentInfo | null>(null);
  const [loading, setLoading] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [justUploaded, setJustUploaded] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);

  // 在启动时打印planId以便调试
  useEffect(() => {
    console.log(`组件初始化，当前计划ID: ${planId}`);
  }, []);

  // 获取附件信息
  const fetchAttachmentInfo = async () => {
    if (!planId) {
      message.error('未找到计划ID');
      return;
    }

    setLoading(true);
    try {
      console.log(`正在获取计划ID为${planId}的附件信息`);
      const response = await getPlanAttachmentInfo(planId);
      console.log(`获取附件信息响应:`, response);
      if (response.code === 1) {
        setAttachment(response.data);
        setJustUploaded(false);
      }
    } catch (error) {
      console.error('获取附件信息失败:', error);
      message.error('获取附件信息失败');
    } finally {
      setLoading(false);
    }
  };

  // 组件加载时获取附件信息
  useEffect(() => {
    if (planId) {
      fetchAttachmentInfo();
    }
    
    // 组件卸载时清除附件状态
    return () => {
      setAttachment(null);
      setJustUploaded(false);
    };
  }, [planId]);

  // 处理下载
  const handleDownload = async () => {
    if (!attachment || !planId) return;
    
    try {
      const response = await downloadPlanAttachment(parseInt(planId));
      const contentType = response.headers?.['content-type'] || 'application/octet-stream';
      const fileName = attachment.fileName;

      const url = window.URL.createObjectURL(
        new Blob([response.data], { type: contentType })
      );
      
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (error) {
      message.error('下载失败');
    }
  };

  const uploadProps: UploadProps = {
    name: 'attachments',
    multiple: false,
    showUploadList: false,
    accept: '.pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png',
    customRequest: async (options) => {
      if (!planId) {
        message.error('未找到计划ID');
        return;
      }

      const { file, onSuccess: uploadSuccess, onError, onProgress } = options;
      
      if (!(file instanceof File)) {
        message.error('上传文件格式错误');
        return;
      }

      setUploading(true);
      setUploadProgress(0);

      try {
        const response = await uploadPlanAttachment(
          parseInt(planId), 
          file,
          (percent) => {
            setUploadProgress(percent);
            onProgress?.({ percent });
          }
        );
        
        if (response.code === 1) {
          message.success('上传成功');
          uploadSuccess?.(response);
          setJustUploaded(true);
          fetchAttachmentInfo();
        } else {
          message.error(response.msg || '上传失败');
          onError?.(new Error(response.msg));
        }
      } catch (error: any) {
        message.error(error.message || '上传失败');
        onError?.(error);
      } finally {
        setUploading(false);
        setUploadProgress(0);
      }
    },
    beforeUpload: (file) => {
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        message.error('文件大小不能超过10MB!');
        return Upload.LIST_IGNORE;
      }

      const allowedTypes = [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'image/jpeg',
        'image/png'
      ];
      
      if (!allowedTypes.includes(file.type)) {
        message.error('不支持的文件类型，仅支持PDF、Word、Excel和JPG/PNG图片格式');
        return Upload.LIST_IGNORE;
      }

      return true;
    },
  };

  // 格式化文件大小
  const formatFileSize = (size: number) => {
    if (size < 1024) {
      return `${size} B`;
    } else if (size < 1024 * 1024) {
      return `${(size / 1024).toFixed(2)} KB`;
    } else {
      return `${(size / (1024 * 1024)).toFixed(2)} MB`;
    }
  };

  const handleCancel = () => {
    if (onCancel) {
      onCancel();
    } else {
      router.back();
    }
  };

  if (!planId) {
    return <div>未找到计划ID</div>;
  }

  return (
    <Space direction="vertical" style={{ width: '100%' }} size="large">
      <div style={{ position: 'relative' }}>
        <Dragger {...uploadProps} disabled={uploading}>
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
          <p className="ant-upload-hint">
            支持单个文件上传，文件大小不能超过10MB
          </p>
        </Dragger>
        
        {uploading && (
          <div style={{ 
            position: 'absolute', 
            top: 0, 
            left: 0, 
            right: 0, 
            bottom: 0, 
            background: 'rgba(255, 255, 255, 0.8)', 
            display: 'flex', 
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '20px'
          }}>
            <Progress 
              type="circle" 
              percent={uploadProgress} 
              status={uploadProgress === 100 ? 'success' : 'active'}
            />
            <div style={{ marginTop: '10px' }}>
              正在上传...{uploadProgress}%
            </div>
          </div>
        )}
      </div>

      <div style={{ marginTop: '20px' }}>
        <Text strong>当前附件：</Text>
        {loading ? (
          <div>加载中...</div>
        ) : attachment ? (
          <List
            itemLayout="horizontal"
            dataSource={[attachment]}
            renderItem={(item) => (
              <List.Item
                actions={[
                  <Button
                    key="download"
                    type="link"
                    icon={<DownloadOutlined />}
                    onClick={handleDownload}
                  >
                    下载
                  </Button>
                ]}
              >
                <List.Item.Meta
                  title={
                    <Space>
                      <span>{item.fileName}</span>
                      {justUploaded && (
                        <Text type="success" style={{ marginLeft: '8px' }}>
                          刚刚上传
                        </Text>
                      )}
                    </Space>
                  }
                  description={
                    <Space>
                      <Text type="secondary">类型：{item.contentType}</Text>
                      <Text type="secondary">大小：{formatFileSize(item.fileSize)}</Text>
                    </Space>
                  }
                />
              </List.Item>
            )}
          />
        ) : (
          <div>暂无附件</div>
        )}
      </div>

      <Button onClick={handleCancel}>返回</Button>
    </Space>
  );
} 